package com.lanou3g.exam.view;

import com.lanou3g.exam.controller.RegisterController;
import com.lanou3g.exam.pojo.User;
import com.lanou3g.exam.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "RegisterServlet", urlPatterns = "/register.action")
public class RegisterServlet extends HttpServlet {
    private RegisterController controller = new RegisterController();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     String username =request.getParameter("username");
     String pwd =MD5Util.MD5WithSalt(request.getParameter("password"));
     String nickname=request.getParameter("nickname");
        User user = new User();
        user.setUsername(username)
                .setPwd(pwd)
                .setNickname(nickname);
        if (controller.register(user)){
            response.sendRedirect("/login.jsp");
        }else {
            fieldMsg(request,response,"注册失败");
        }

    }
    private void fieldMsg(HttpServletRequest request,
                          HttpServletResponse response,
                          String msg) throws ServletException, IOException {

        String path = "/register.jsp";
        request.setAttribute("msg", msg);
        request.setAttribute("path", path);
        //点击链接返回,或者5秒返回(留头不留尾)
        response.setStatus(302);
        response.setHeader("refresh", "5, URL =/register.jsp");
        request.getRequestDispatcher("msg.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
